const db = require('../db/index');

//查询所有问答
exports.getAllQuestion = (req,res)=>{
    const sql =`SELECT q.*,u.username,u.avatar FROM user u, question q where u.user_id = q.user_id;`;
    db.query(sql, (err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取失败！');

        res.send({
            status: 0,
            mesage: "获取问答列表成功!",
            retdata: results
        })
    })
}

//添加校园问答
exports.addQuestion = (req, res) => {

    const questionInfo = {
        ...req.body,
        user_id: req.user.user_id,
    }

    const sql = `INSERT into question set ?;`;
    db.query(sql, questionInfo, (err, results) => {
        if (err) return res.cc(err);

        if (results.affectedRows !== 1) return res.cc('增加校园问答失败！');

        res.cc("新添校园问答成功！", 0)
    })
}

//查询一条问答下所有评论
exports.getAllComment = (req,res)=>{
    const sql =`SELECT u.username,u.avatar,c.content,c.comment_id FROM user u,comment c where c.question_id = ? and c.user_id = u.user_id;`;
    db.query(sql, req.body.question_id,(err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取一条问答下所有评论失败！');

        res.send({
            status: 0,
            mesage: "获取一条问答下所有评论成功!",
            retdata: results
        })
    })
}

//添加评论
exports.addComment = (req, res) => {

    const commentInfo = {
        ...req.body,
        user_id: req.user.user_id,
    }

    const sql = `INSERT into comment set ?;`;
    db.query(sql, commentInfo, (err, results) => {
        if (err) return res.cc(err);

        if (results.affectedRows !== 1) return res.cc('增加校园问答评论失败！');

        res.cc("新添校园问答评论成功！", 0)
    })
}

//查询自己发布的问答
exports.getSelfQuestion = (req,res)=>{
    const sql =`SELECT * FROM question where user_id = ?;`;
    db.query(sql, req.body.user_id,(err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取自己发布的问答失败！');

        res.send({
            status: 0,
            mesage: "获取自己发布的问答成功!",
            retdata: results
        })
    })
}

//管理员查询所有问答
exports.getAdminAllQuestion = (req,res)=>{
    const sql =`SELECT * from question;`;
    db.query(sql, (err, results) => {
        if (err) return res.cc(err);
   
        if (results.results ===  0) return res.cc('获取管理员问答列表失败！');

        res.send({
            status: 0,
            mesage: "获取管理员问答列表成功!",
            retdata: results
        })
    })
}

//删除问答
exports.deleteQuestion = (req,res) => {
    const sql = `DELETE FROM question WHERE question_id = ?;`
    db.query(sql, req.body.question_id, (err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows != 1) return res.cc('删除问答失败！')

        res.cc("删除问答成功！",0)
    })
}